package com.xyy.ebattery.tcp.app;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xyy.common.constant.MsgCodeEnum;
import com.xyy.ebattery.tcp.common.content.DeviceTypeContent;
import com.xyy.exception.BizException;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;


/**
 * @Description TODO
 * @author JIA BOYAN
 * date 2025/06/16  17.41
 */
@ChannelHandler.Sharable
@Component
@Slf4j
public class ServerHandler extends SimpleChannelInboundHandler<String> {

    @Autowired
    private ChannelManager channelManager;

    private final ObjectMapper objectMapper = new ObjectMapper();
    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        channelManager.addChannel(ctx.channel());
        System.out.println("Client connected: " + ctx.channel().remoteAddress());
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) {

        Map<String,Object>messageMap=null;
        try {
            messageMap=objectMapper.readValue(msg,Map.class);
        } catch (JsonProcessingException e) {
            throw new BizException(MsgCodeEnum.PARAM_EXCEPTION,"参数异常");
        }
        if(messageMap==null){
            throw new BizException(MsgCodeEnum.NOT_NULL,"不能为null");
        }

        Object devIdObj = messageMap.get("devType");
        log.info("devIdObj:{}",devIdObj.toString());

        if (!(devIdObj instanceof Integer)) {
            throw new BizException(MsgCodeEnum.PARAM_EXCEPTION, "devId 不是合法的整数");
        }

        Integer devId=(Integer)devIdObj;




        //TODO 在这里去写接口
        if(devId.equals(DeviceTypeContent.BATTERY)){
            ctx.writeAndFlush("电池");
            log.info("Received: " + "电池" + " From: " + ctx.channel().remoteAddress());
        }else{
            ctx.writeAndFlush("换电柜");
            log.info("Received: " + "换电柜" + " From: " + ctx.channel().remoteAddress());

        }




        // 审计日志
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        System.err.println("Error: " + cause.getMessage());
        ctx.close();
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        channelManager.removeChannel(ctx.channel());
        System.out.println("Client disconnected: " + ctx.channel().remoteAddress());
    }
}